/**
	Copyright (c) 2010 ATTi 
	All rights reserved.
	Author: Michael Shu
	Date: 10/7/2010
*/

trigger AccountAASFieldUpdateTrigger on Account (before insert, before update, after update) {
	Set<ID> accountAASRecordTypeID = AASFieldUpdateHelperClass.getAccountAASRecordTypeID();
	if(trigger.isBefore){
		List<Account> accounts = new List<Account>();
		Set<ID> ownerIds = new Set<ID>();
		if(trigger.isInsert){
			for(Account a : trigger.new){
				if(accountAASRecordTypeID.contains(a.RecordTypeId)){
					accounts.add(a);
					ownerIds.add(a.OwnerId);
				}
			}
		}else if(trigger.isUpdate){
			for(Account a : trigger.new){
				Account oldAcc = trigger.oldMap.get(a.Id);
				if(a.OwnerId != oldAcc.OwnerId && accountAASRecordTypeID.contains(a.RecordTypeId)){
					accounts.add(a);
					ownerIds.add(a.OwnerId);
				}
			}
		}
		if(!accounts.isEmpty()){
			AASFieldUpdateHelperClass.updateAASAccountfieldsInBeforeEvent(accounts, ownerIds, trigger.oldMap);
		}
	}else if(trigger.isAfter){
		Set<ID> accountIds = new Set<ID>();
		if(trigger.isUpdate){
			for(Account a : trigger.new){
				Account oldAcc = trigger.oldMap.get(a.Id);
				if((a.AAS_Agency_Name__c != oldAcc.AAS_Agency_Name__c || a.Master_Client__c != oldAcc.Master_Client__c) && accountAASRecordTypeID.contains(a.RecordTypeId)){
					accountIds.add(a.Id);
				}				
			}
			if(!accountIds.isEmpty()){
				AASFieldUpdateHelperClass.updateAASoppsWithoutChange(accountIds);
			}
		}
	}
}